<template>
  <div id="leaflet3DBox"></div>
</template>

<script>
import CONTANT from "@/lib/contant.js";
import * as THREE from "@/static/three.module.js";
import { OrbitControls } from "@/static/controls/OrbitControls.js";
import {
  CSS3DRenderer,
  CSS3DObject,
} from "@/static/renderers/CSS3DRenderer.js";
import "leaflet/dist/leaflet.css";
import L from "leaflet";

export default {
  data() {
    return {
      map: null,
    };
  },
  mounted() {
    let camera, scene, renderer;
    let controls;

    init();
    animate();

    var subdomains = ["0", "1", "2", "3", "4", "5", "6", "7"];
    var image = L.tileLayer(
      "https://t{s}.tianditu.gov.cn/img_c/wmts?layer=img&style=default&tilematrixset=c&Service=WMTS&Request=GetTile&Version=1.0.0&Format=tiles&TileMatrix={z}&TileCol={x}&TileRow={y}&tk=23c64b6db1d90eaeb7516746514ef956",
      {
        maxZoom: 17,
        tileSize: 256,
        zoomOffset: 1,
        subdomains: subdomains,
      }
    );
    this.map = L.map("leafletMap", {
      crs: L.CRS.EPSG4326,
      layers: [image],
      zoomControl: false,
      attributionControl: false,
    }).setView([43.863033, 125.323256], 12);

    function init() {
      camera = new THREE.PerspectiveCamera(
        40,
        (window.innerWidth - CONTANT.LEFT_WIDTH) /
          (window.innerHeight - CONTANT.TOP_HEIGHT),
        1,
        10000
      );

      camera.position.z = 1500;
      scene = new THREE.Scene();

      const element = document.createElement("div");
      element.id = "leafletMap";

      const objectCSS = new CSS3DObject(element);
      objectCSS.position.x = 0;
      objectCSS.position.y = 0;
      objectCSS.position.z = 0;
      scene.add(objectCSS);

      renderer = new CSS3DRenderer();
      renderer.setSize(
        window.innerWidth - CONTANT.LEFT_WIDTH,
        window.innerHeight - CONTANT.TOP_HEIGHT
      );
      document.getElementById("leaflet3DBox").appendChild(renderer.domElement);

      controls = new OrbitControls(camera, renderer.domElement);
      controls.minDistance = 500;
      controls.maxDistance = 6000;
      controls.update();

      window.addEventListener("resize", onWindowResize);
    }

    function onWindowResize() {
      camera.aspect =
        (window.innerWidth - CONTANT.LEFT_WIDTH) /
        (window.innerHeight - CONTANT.TOP_HEIGHT);
      camera.updateProjectionMatrix();
      renderer.setSize(
        window.innerWidth - CONTANT.LEFT_WIDTH,
        window.innerHeight - CONTANT.TOP_HEIGHT
      );
      render();
    }

    function animate() {
      requestAnimationFrame(animate);
      render();
      controls.update();
    }

    function render() {
      renderer.render(scene, camera);
    }
  },
};
</script>

<style>
#leaflet3DBox {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: black;
}

#leafletMap {
  width: 1000px;
  height: 600px;
  box-shadow: 0px 0px 200px rgba(1, 252, 20, 0.5);
}
</style>
